<script setup>
import { http } from "../../services/service";
import { useUserStore } from "../../store/index";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { covers } from "../../enums/cover";
import { showConfirmDialog } from "vant";
import _ from "lodash";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
const store = useUserStore();
const props = defineProps(["cards", "cardId", "type"]);
const currentPage = ref(0);
const totalItem = ref(0);
const i18nUse = useI18n();

const cards = ref([]);
const getCards = () => {
  if (loading.value) {
    return;
  }
  currentPage.value = currentPage.value + 1;
  http
    .get(
      `/api/v1/center/myBag?telegramId=${store.getUser?.telegramId}&cardTypeId=${props.cardId}&page=${currentPage?.value}`
    )
    .then(
      (response) => {
        const pagedata = response?.data?.data?.userCards;
        if (pagedata?.length) {
          if (currentPage.value === 1) {
            cards.value = pagedata;
          } else {
            cards.value = _.uniqBy([...cards.value, ...pagedata], "id");
          }
          loading.value = false;
        }
        if (
          currentPage.value == response?.data?.data?.totalPages ||
          pagedata.length === 0
        ) {
          finished.value = true;
        }
      },
      () => {}
    );
};

const getSellCard = () => {
  if (loading.value) {
    return;
  }
  currentPage.value = currentPage.value + 1;
  http
    .get(
      `/api/v1/center/pushAdSellSerarchMyBag?telegramId=${store.getUser?.telegramId}&cardTypeId=${props.cardId}&page=${currentPage.value}`
    )
    .then(
      (response) => {
        const pagedata = response?.data?.data?.userCards;
        if (pagedata?.length) {
          if (currentPage.value === 1) {
            cards.value = pagedata;
          } else {
            cards.value = _.uniqBy([...cards.value, ...pagedata]);
          }
          loading.value = false;
        }
        if (
          currentPage.value == response?.data?.data?.totalPages ||
          pagedata.length === 0
        ) {
          finished.value = true;
        }
      },
      () => {}
    );
};

const getCard = (card) => {
  return covers[card.cardId]?.cover;
};
const checked = ref();
const loading = ref(false);
const finished = ref(false);

const onLoad = () => {
  if (props.type === "sell") {
    getSellCard();
  } else {
    getCards();
  }
};

const sellCard = (card) => {
  showConfirmDialog({
    title: i18nUse.t("sell"),
    message: `${i18nUse.t("confirm_to_sell")} 【${
      i18nUse.locale.value === "en" ? card.enName : card.zhName
    }】`,
    cancelButtonColor: "#9799A0",
    confirmButtonColor: "#fff",
    cancelButtonText: i18nUse.t("cancel"),
    confirmButtonText: i18nUse.t("confirm"),
  })
    .then(() => {
      router.push({
        path: "/myAdd",
        query: {
          cardInfo: JSON.stringify({ card }),
          from: "sellList",
        },
      });
    })
    .catch(() => {});
};
const calculateTimeDifference = (startDate, endDate) => {
  // Check if both parameters are valid dates
  if (!(startDate instanceof Date && endDate instanceof Date)) {
    throw new Error("Both parameters must be valid Date objects");
  }
  const diffMilliseconds =
    endDate.getTime() + 24 * 60 * 60 * 1000 - startDate.getTime();
  return diffMilliseconds;
};

const getCountDown = (card) => {
  return calculateTimeDifference(new Date(), new Date(card.wakeTime));
};

const selectedCard = ref();

const returnToPool = (card) => {
  show.value = true;
  selectedCard.value = card;
};
const onConfirm = () => {
  http
    .get(
      `/api/v1/center/destroyCard?telegramId=${store.getUser?.telegramId}&userCardId=${selectedCard.value?.id}`
    )
    .then(
      (response) => {
        if (response?.data?.code === 200) {
          if (props.type === "sell") {
            getSellCard();
          } else {
            getCards();
          }
        } else {
          showToast(response?.data?.message);
        }
      },
      () => {}
    );
};
const show = ref(false);
</script>

<template>
  <van-dialog
    v-model:show="show"
    show-cancel-button
    :confirm-button-text="$t('confirm')"
    :cancel-button-text="$t('cancel')"
    cancel-button-color="#95979E"
    @confirm="onConfirm"
  >
    <div class="withDrawDialog">
      <div>
        <div style="text-align: center">{{ $t("return_to_pool") }}</div>
        <div style="margin-top: 10px">{{ $t("return_back_msg") }}</div>
      </div>
    </div>
  </van-dialog>
  <div style="position: relative; min-height: 70vh">
    <van-list
      v-model="loading"
      :finished="finished"
      :finished-text="$t('no_more')"
      :loading-text="$t('loading')"
      @load="onLoad"
      :offset="0"
    >
      <van-radio-group v-model="checked" shape="dot">
        <div
          v-for="card in cards"
          class="card-container"
          :style="{ paddingBottom: card.turnoverNumber >= 12 ? '40px' : 0 }"
        >
          <div class="img-container">
            <span v-if="card.wakeStatus === 'yes'" class="count-down-container"
              >{{ $t("countdownTxt") }}
              <van-count-down
                style="padding-left: 5px"
                millisecond
                :time="getCountDown(card)"
                format="HH:mm:ss"
              />
            </span>
            <span
              v-if="card.wakeStatus === 'not'"
              class="count-down-container"
              style="background-color: #ffab00"
            >
              <span v-if="card.cardStatus === 'normal'">{{
                $t("can_be_sell")
              }}</span>
              <span v-if="card.cardStatus === 'selling'">{{
                $t("on_sell")
              }}</span>
            </span>
            <img :src="getCard(card)" width="100%" height="100%" alt="" />
          </div>
          <div class="content-container">
            <div
              style="
                font-size: 14px;
                font-weight: 400;
                display: flex;
                justify-content: space-between;
              "
            >
              <van-radio
                :name="card.id"
                v-if="type === 'sell'"
                @click="sellCard(card)"
              ></van-radio>
            </div>
            <div
              style="
                font-size: 16px;
                font-weight: 500;
                display: flex;
                justify-content: space-between;
                margin-right: -10px;
              "
            >
              <span>{{
                i18nUse?.locale.value === "en" ? card.enName : card.zhName
              }}</span>
              <span>
                <span style="font-size: 10px">Odysseus</span>【{{
                  card.cardCode
                }}】
              </span>
            </div>
            <div class="price-container">
              <span style="color: #9699a2"> {{ $t("releasePrice") }} </span
              ><span>{{ card.releasePrice }}{{ $t("star") }}</span>
            </div>
            <div class="price-container">
              <span style="color: #9699a2"> {{ $t("buyPrice") }}</span
              ><span>{{ card.lastPrice }}{{ $t("star") }}</span>
            </div>
            <div class="price-container">
              <span style="color: #9699a2">{{ $t("currentPrice") }}</span
              ><span>{{ card.currentPrice }}{{ $t("star") }}</span>
            </div>
            <div class="price-container">
              <span style="color: #9699a2">{{ $t("inflationRate") }}</span
              ><span>{{ card?.cardGrowthRate * 100 }}%</span>
            </div>
            <div class="price-container">
              <span style="color: #9699a2">{{ $t("changeRate") }}</span
              ><span>{{ card.turnoverNumber }} </span>
            </div>
          </div>
          <div
            class="return-to-poll-container"
            v-if="card.turnoverNumber >= 12"
          >
            <van-button type="primary" size="small" @click="returnToPool(card)">
              {{ $t("return_to_pool") }}
            </van-button>
          </div>
        </div>
      </van-radio-group>
    </van-list>
  </div>
</template>

<style scoped lang="less">
.withDrawDialog {
  padding: 40px;
  font-size: 16px;
  > div {
    color: #fff !important;
  }
}
.return-to-poll-container {
  position: absolute;
  bottom: 0;
  width: 100%;
  button {
    width: 100%;
    background-image: linear-gradient(to right, #9ba8ff, #4a61f9);
    border-radius: 10px;
  }
}
.pagination-container {
  width: 90%;
  position: absolute;
  bottom: 5%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.card-container {
  position: relative;
  display: flex;
  justify-content: space-between;
  height: 186px;
  width: 90%;
  margin: 24px auto 0 auto;

  .count-down-container {
    position: absolute;
    left: 0;
    top: 0;
    background-color: #4a61f9;
    border-radius: 9px 0px 9px 0px;
    font-size: 12px;
    height: 24px;
    width: 144px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .img-container {
    width: 49%;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .content-container {
    width: 49%;
    line-height: 25px;
  }

  .price-container {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
  }
}
</style>
